package 第三周;

/**
 * @author xhw
 */

public class 最长公共前缀 {
    public static void main(String[] args) {
        String[] strs = {"flower", "flow", "flight"};
        System.out.println(longestCommonPrefix(strs));

        String[] strs2 = {"dog", "racecar", "car"};
        System.out.println(longestCommonPrefix(strs2));
    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0)
            return "";
        String first = strs[0];
        for (int i = 1; i < strs.length; i++) {
            while (strs[i].indexOf(first) != 0) {
                first = first.substring(0, first.length() - 1);
                if (first.isEmpty())
                    return "";
            }
        }
        return first;
    }
}